package com.echo.register.order.api;

import com.echo.register.common.result.Result;
import com.echo.register.enums.PaymentTypeEnum;
import com.echo.register.order.service.PaymentService;
import com.echo.register.order.service.WeixinService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {
    @Autowired
    private WeixinService weixinService;
    @Autowired
    private PaymentService paymentService;
    /**
     * 下单 生成二维码
     */
    @GetMapping("/createNative/{orderId}")
    public Result<Map<String,Object>> createNative(
        @ApiParam(name = "orderId", value = "订单id", required = true)
        @PathVariable("orderId") Long orderId) {
        Map<String, Object> aNative = weixinService.createNative(orderId);
        // todo 发短信通知

        return Result.ok(aNative);
    }
    //对接微信查询接口，查询支付状态 以及处理 支付完成后的业务
    @GetMapping("/queryPayStatus/{orderId}")
    public Result<?> queryPayStatus(@PathVariable Long orderId){
        Map<String, String> resultMap = weixinService.queryPayStatus(orderId, PaymentTypeEnum.WEIXIN.getComment());
        if (resultMap == null) {
            return Result.fail().message("支付失败");
        }
        if (resultMap.get("return_code").equals("SUCCESS")
                && resultMap.get("result_code").equals("SUCCESS")
                && resultMap.get("trade_state").equals("SUCCESS")) {
            // 支付成功更新支付记录&订单状态&对接医院系统更新订单
            paymentService.paySuccess(resultMap.get("out_trade_no"),PaymentTypeEnum.WEIXIN.getStatus(), resultMap);
            return Result.ok().message("支付成功");
        }
        return Result.ok().message("支付中");
    }
}